package com.bbbug.coree.controller;

import cn.hutool.core.img.Img;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.bbbug.coree.service.SongService;
import com.bbbug.coree.utils.MiscUtil;
import com.bbbug.coree.entity.ReturnData;
import com.bbbug.coree.utils.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/api")
@RestController
@CrossOrigin(origins = "${myweb-path}")
public class miscController {
    @Value("${mywebapi-path}")
    String myWebApiPath;
    private static HashMap<String, Object> hashMap = new HashMap<>();
    @Autowired
    JavaMailSender javaMailSender;
    RedisTemplate redisTemplate = SpringUtils.getBean("redistemp");
    @Autowired
    private SongService songService;

    @RequestMapping("system/time")
    ReturnData getTime() {
        hashMap.put("time", System.currentTimeMillis());
        return new ReturnData(200, "fuck world", hashMap);
    }


    @Value("${spring.mail.from}")
    private String emailsendername;

    @RequestMapping("/sms/email")
    ReturnData sendEmail(@RequestBody Map mp) {
        try {
            String email = (String) mp.get("email");
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(emailsendername);
            message.setSubject("这是你的验证码");
            message.setTo(email);
            String s = RandomUtil.randomString(6);
            message.setText(s);
            BoundHashOperations emailcode = redisTemplate.boundHashOps("emailcode");
            JSONObject ishave = (JSONObject) emailcode.get(email);
            if (ishave != null && ishave.getLong("time") >= System.currentTimeMillis())
                return new ReturnData(403, "发送过于频繁 请过一会再发", "");
            javaMailSender.send(message);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", s);
            jsonObject.put("time", System.currentTimeMillis() + 10 * 60 * 1000);
            emailcode.put(email, jsonObject);
            return new ReturnData(200, "验证码十分钟内有效 请注意查收", "");
        } catch (Exception e) {

        }
        return new ReturnData(500, "输入正常的邮箱", "");
    }

    @Value("${web.upload-path}")
    String mypath;

    @RequestMapping("attach/uploadimage")
    ReturnData uploadImage(@RequestParam("file") MultipartFile file, @RequestParam("access_token") String access_token) throws Exception {
        String s = file.getOriginalFilename().split("\\.")[1];
        new File(mypath + s).mkdirs();
        String s1 = RandomUtil.randomString(13);
        String newfilename = s + "//" + s1 + "." + s;
        File file1 = new File(mypath + newfilename);
        long size = file.getSize();
        long fazhi = 1024 * 1024;
        double re = size <= fazhi ? 1 : Math.pow(fazhi * 1.0 / size, 0.3);
        try (FileOutputStream fileOutputStream = new FileOutputStream(file1)) {
            Img.from(file.getInputStream())
                    .setQuality(re)
                    .write(fileOutputStream);
        } catch (Exception e) {
            return new ReturnData(200, "上传失败", e.getMessage());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("attach_status", 0);
        map.put("attach_path", myWebApiPath + "/uploads/" + newfilename);
        map.put("attach_thumb", myWebApiPath + "/uploads/" + newfilename);
        map.put("attach_type", s);
        map.put("attach_size", file1.length());
        map.put("attach_updatetime", System.currentTimeMillis());
        map.put("attach_createtime", System.currentTimeMillis());
        map.put("attach_user", MiscUtil.verifyToken(access_token));
        return new ReturnData(200, "上传成功", map);
    }

    @RequestMapping("/attach/uploadHead")
    ReturnData uploadHead(@RequestParam("file") MultipartFile file, @RequestParam("access_token") String access_token) throws Exception {
        return uploadImage(file, access_token);
    }

    @RequestMapping("/attach/uploadMusic")
    ReturnData uploadMusic(@RequestParam("file") MultipartFile file, @RequestParam("access_token") String access_token)  {
        try{
            String[] split = file.getOriginalFilename().split("\\.");
            String fileType = split[split.length-1];
            new File(mypath + fileType).mkdirs();
            String newfilename = fileType + "/" + RandomUtil.randomString(13) + "." + fileType;
            File localFile = new File(mypath + newfilename);
            byte[] bytes = file.getBytes();
            FileUtil.writeBytes(bytes, localFile);
            long songId = RandomUtil.randomLong((int) -1e15, -1);
            HashMap<String, Object> result = new HashMap<>();
            result.put("attach_path", newfilename);
            result.put("attach_id", songId);
            return new ReturnData(200, "ok", result);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnData(500, "error", null);
    }

}
